﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Reporting.WebForms;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Web.Report_Template;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace Web.Invoice
{
    public partial class InvoiceReport : System.Web.UI.Page
    {
        static string requestEdit = string.Empty;
        static long? assignedToID = null;
        static USER user;


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                assignedToID = null;
                user = (USER)Session["User"];
                if (user != null)
                {
                    ROLE r = RoleService.GetRoleByID((long)user.ROLE_ID);
                    if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
                    {
                        assignedToID = user.ID;
                    }
                    string InvoiceID = Request.QueryString["InvoiceID"];
                    INVOICE_DETAIL invoiceDetail = InvoiceService.GetInvoiceDetailByID(Convert.ToInt64(InvoiceID), assignedToID);

                    ReportViewer1.ProcessingMode = ProcessingMode.Local;
                    ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Report_Template/Report1.rdlc");
                    DataSet1 ds = new DataSet1();
                    DataTable t = ds.Tables.Add("ChungTu");
                    t.Columns.Add("ITEM", Type.GetType("System.String"));
                    t.Columns.Add("DESCRIPTION", Type.GetType("System.String"));
                    t.Columns.Add("UNIT_PRICE", Type.GetType("System.Double"));
                    t.Columns.Add("QUANTITY", Type.GetType("System.Double"));
                    t.Columns.Add("AMOUNT", Type.GetType("System.Double"));
                    //    t.Columns.Add("TOTAL", Type.GetType("System.Double"));                    
                    double? thanhtien = 0;
                    t = GetItemListDataTable(invoiceDetail.ITEM_ID, t, ref thanhtien);

                    List<ReportParameter> Parameters = new List<ReportParameter>();
                    ReportParameter param = default(ReportParameter);
                    param = new ReportParameter("CustomerName", invoiceDetail.CONTACT_NAME);
                    Parameters.Add(param);
                    param = new ReportParameter("CompanyName", invoiceDetail.ORGANIZATION_NAME);
                    Parameters.Add(param);
                    param = new ReportParameter("PostalCode", invoiceDetail.HOME_POSTAL_CODE);
                    Parameters.Add(param);
                    param = new ReportParameter("Address", invoiceDetail.OFFICE_ADDRESS);
                    Parameters.Add(param);
                    param = new ReportParameter("ContactNumber", invoiceDetail.PHONE_MOBILE);
                    Parameters.Add(param);
                    DateTime date = DateTime.Now;
                    param = new ReportParameter("DATE", date.Day + "/" + date.Month + "/" + date.Year);
                    Parameters.Add(param);
                    if ((DateTime)invoiceDetail.DUE_DATE != null)
                        date = (DateTime)invoiceDetail.DUE_DATE;
                    param = new ReportParameter("VALID_UNTIL", date.Day + "/" + date.Month + "/" + date.Year);
                    Parameters.Add(param);
                    param = new ReportParameter("ORDER", invoiceDetail.INVOICE_NUMBER);
                    Parameters.Add(param);
                    DocTien dt = new DocTien();
                    param = new ReportParameter("BangChu", dt.DocTienBangChu(Convert.ToDouble(thanhtien), " đồng"));
                    Parameters.Add(param);

                    ReportViewer1.LocalReport.SetParameters(Parameters);
                    ReportDataSource datasource = new ReportDataSource("DataSet1", t);
                    ReportViewer1.LocalReport.DataSources.Clear();
                    ReportViewer1.LocalReport.DataSources.Add(datasource);
                    ReportViewer1.LocalReport.Refresh();
                    ReportViewer1.DataBind();
                }
            }
        }
        private DataTable GetItemListDataTable(long? itemID, DataTable dt, ref double? thanhtien)
        {
            List<ITEM_DETAILS> itemDetails = ItemService.GetListItemDetailByItemID(itemID);
            if (itemDetails != null)
            {
                for (int i = 0; i < itemDetails.Count; i++)
                {
                    ITEM_DETAILS item = itemDetails[i];
                    DataRow dr = dt.NewRow();
                    dr["ITEM"] = i + 1;
                    dr["DESCRIPTION"] = item.DESCRIPTION;
                    dr["UNIT_PRICE"] = item.UNIT_PRICE;
                    dr["QUANTITY"] = item.QUANTITY;
                    dr["AMOUNT"] = item.PRICE;
                    //   dr["TOTAL"] = item.PRICE;
                    thanhtien += item.PRICE;
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }

        protected void print_Click(object sender, EventArgs e)
        {
            Warning[] warnings;
            string[] streamids;
            string mimeType;
            string encoding;
            string extension;

            byte[] bytes = ReportViewer1.LocalReport.Render("PDF", null, out mimeType,
                           out encoding, out extension, out streamids, out warnings);

            FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("output.pdf"), FileMode.Create);
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();

            //Open exsisting pdf
            Document document = new Document(PageSize.A4);
            PdfReader reader = new PdfReader(HttpContext.Current.Server.MapPath("output.pdf"));
            //Getting a instance of new pdf wrtiter
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(
               HttpContext.Current.Server.MapPath("Print.pdf"), FileMode.Create));
            document.Open();
            PdfContentByte cb = writer.DirectContent;

            int i = 0;
            int p = 0;
            int n = reader.NumberOfPages;
            Rectangle psize = reader.GetPageSize(1);

            float width = psize.Width;
            float height = psize.Height;

            //Add Page to new document
            while (i < n)
            {
                document.NewPage();
                p++;
                i++;

                PdfImportedPage page1 = writer.GetImportedPage(reader, i);
                cb.AddTemplate(page1, 0, 0);
            }

            //Attach javascript to the document
            PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
            writer.AddJavaScript(jAction);
            document.Close();

            //Attach pdf to the iframe
            frmPrint.Attributes["src"] = "Print.pdf";
        }
    }
}